<?php
	require('config.php');

	//$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
	$msg = array();
	$postStr = file_get_contents('php://input');
	$msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
	file_put_contents('wechatpayhuidiao.txt',json_encode($msg).PHP_EOL,FILE_APPEND);
	
	// 测试使用数据
	// $msg = json_decode('{"appid":"wx1b23dc20249ad1e7","attach":"67","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1496579722","nonce_str":"uzlwm0109n9v25wtwydfx4sc47d6elfd","openid":"oQSBl07m48qavU8Ad8N40LSSe2fg","out_trade_no":"14965797221512462308730","result_code":"SUCCESS","return_code":"SUCCESS","sign":"BC558242CDFB7412F1C3317DD0208C18","time_end":"20180128213031","total_fee":"1","trade_type":"APP","transaction_id":"4200000076201801282641593433"}', true);
	// print_r($msg);
	// echo $msg['result_code'];

	// 连接跑腿数据库
	$paotuiDB = ptconnect();
	// print_r($paotuiDB);
	// exit();
	if($msg['result_code']=='SUCCESS'){
		$order_id = $msg['attach'];
		$sql = "SELECT * FROM ".$pt."_send_order where id='{$order_id}'";
		$result = $paotuiDB->query($sql);
		while($row=$result->fetch_assoc()){
			$send_order=$row;//将取得的所有数据赋值给send_order数组
		}

		if ($send_order['pay_status'] != 0) {
			echo 'SUCCESS';
			return;
		}
		// print_r($send_order);

		$sql="update ".$pt."_send_order set pay_status=1,pay_type=2 where id='{$order_id}'";
		// print_r($sql);
		// exit();
		$result=$paotuiDB->query($sql);
		
		$user_id = $send_order['uid'];
		$sql = "SELECT * FROM ".$oto."_users where userId='{$user_id}'";
		$result = $db->query($sql);
		while($row=$result->fetch_assoc()){
			$user_info=$row;//将取得的所有数据赋值给send_order数组
		}
		// print_r($user_info);
		$needPay_lin = $msg['total_fee']/100;
		$user_money_lin = $user_info['userMoney'];
		$time2 = time();
		$third_trade_no = (string)$msg['out_trade_no'];
		// echo $third_trade_no;
		$sql="INSERT INTO ".$oto."_money_record (`userid`,`orderNo`,`money`,`balance`,`time`,`IncDec`,`type`,`remark`,`payWay`,`third_trade_no`) VALUES ('$user_id','$order_id','$needPay_lin','$user_money_lin','$time2','0','6','消费','2','$third_trade_no')";
		// print_r($sql);
		$result=$db->query($sql);
		echo 'SUCCESS';
	}
	
?>